package com.ktjiaoyu.ktmall.servlet.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ktjiaoyu.ktmall.service.CartService;
import com.ktjiaoyu.ktmall.service.impl.CartServiceImpl;
import com.ktjiaoyu.ktmall.utils.R;
import com.ktjiaoyu.ktmall.utils.RedisUtil;
import com.ktjiaoyu.ktmall.utils.RequestUtil;
import com.ktjiaoyu.ktmall.vo.CartVo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@WebServlet(name="CartServlet",urlPatterns = "/api/cart")
public class CartServlet extends HttpServlet {
    private CartService cartService = new CartServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        R result=null;
        String opr = request.getParameter("opr");
        if (opr==null){
            opr="";
        }
        String userId = RedisUtil.getUserIdFromToken(request);
        switch (opr){
            case "list":
                result = doGetCartList(userId);
                break;
            case "items":
                String idsStr = request.getParameter("ids");
                List<String> ids = Arrays.asList(idsStr.split(",")).stream().collect(Collectors.toList());
                result =R.ok().data(cartService.getItemsByIds(ids));
                break;
            case "count":
                result = R.ok().data(cartService.getCartCount(userId));
                break;
            default:
                result = R.fail().msg("未知操作");
        }
        out.print(JSON.toJSONString(result));
        out.flush();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        R result=null;
        String opr = request.getParameter("opr");
        if (opr==null)opr="";
        String userId = RedisUtil.getUserIdFromToken(request);
        String body = RequestUtil.readBody(request);
        JSONObject params = null;
        if (body!=null&&!body.isEmpty()){
            params = JSON.parseObject(body);
        }else {
            params = new JSONObject();
        }
        switch (opr){
            case "add":
                result = doAddToCart(userId,params);
                break;
            default:
                result = R.fail().msg("未知操作");
        }
        out.print(JSON.toJSONString(result));
        out.flush();
        out.close();
    }
    private R doGetCartList(String userId) {
        List<CartVo> cartList = cartService.getCartList(userId);
        return R.ok().data(cartList);
    }
    private R doAddToCart(String userId, JSONObject params) {
        String productId = params.getString("productId");
        Integer quantity = params.getInteger("quantity");
        if (productId==null||quantity==null||quantity<=0){
            return R.fail().msg("参数错误");
        }
        String cartId = cartService.addToCart(userId,productId,quantity);
        return cartId!=null?R.ok().data(cartId).msg("添加成功"):R.fail().msg("添加失败");
    }
}
